package de.tsystems.dict.webservice.impl;


import de.tsystems.dict.api.LanguageService;
import de.tsystems.dict.api.TranslationService;
import de.tsystems.dict.api.WordService;
import de.tsystems.dict.model.Language;
import de.tsystems.dict.model.Word;
import de.tsystems.dict.webservice.TranslationManipulationService;
import org.apache.commons.lang.StringUtils;

import javax.inject.Inject;
import javax.inject.Named;
import java.util.List;

@Named("translationManipulationService")
class TranslationManipulationServiceImpl implements TranslationManipulationService {

    @Inject
    @Named("translationService")
    private TranslationService translationService;

    @Inject
    @Named("wordService")
    private WordService wordService;

    @Inject
    @Named("languageService")
    private LanguageService languageService;


    public TranslationService getTranslationService() {
        return translationService;
    }

    public void setTranslationService(TranslationService translationService) {
        this.translationService = translationService;
    }

    public WordService getWordService() {
        return wordService;
    }

    public void setWordService(WordService wordService) {
        this.wordService = wordService;
    }

    public LanguageService getLanguageService() {
        return languageService;
    }

    public void setLanguageService(LanguageService languageService) {
        this.languageService = languageService;
    }

    @Override
    public String greetUser() {
        return "Hello";
    }

    @Override
    public String countTranslations() {
        return String.format("%s", translationService.listAll().size());
    }

    @Override
    public String add(TranslationInfo info) {
        Language left = languageService.findLanguage(info.getLeftLanguage());
        if (null == left) {
            return "left language not found";
        }
        String leftWordText = StringUtils.trimToEmpty(info.getLeftWord());
        Word wordLeft = wordService.findByTextAndLanguage(leftWordText, left);
        if (null == wordLeft) {
            wordLeft = wordService.create(leftWordText, left);
        }

        Language right = languageService.findLanguage(info.getRightLanguage());
        if (null == right) {
            return "right language not found";
        }
        String rightWordText = StringUtils.trimToEmpty(info.getRightWord());
        Word wordRight = wordService.findByTextAndLanguage(rightWordText, right);
        if (null == wordRight) {
            wordRight = wordService.create(rightWordText, right);
        }
        if (!translationService.createTranslation(wordLeft, wordRight)) {
            return "Translation already exists";
        }


        return "Ok";
    }

    @Override
    public List<Word> list() {
        return wordService.listAll();
    }

}


